package com.jhws.core.shiro.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.DateUtil;
import com.jhws.util.LogHelper;

public class FormAutchFilter extends FormAuthenticationFilter{
	
	@Resource
	ITblUserDimService IUserService;
	
	/* 
	 *  @create time : 2016-10-11 上午10:58:50
	 *  @author : Alex Tan
	 *  @comments : 假如已经登录过，则直接跳转loginindex, 假如未登录，返回false,由onAccessDenied处理
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) {
	    /* 防止重定向循环 */
	    if(null != request.getParameter("anotherUser"))
	        return true;

	    String logName = request.getParameter("logName");
		// TODO Auto-generated method stub
		if(super.isAccessAllowed(request, response, mappedValue)){
			try {
			    TblUserDimBo user = (TblUserDimBo)WebUtils.toHttp(request).getSession().getAttribute(TblUserDimBo.USER_INFO_REFERENCE);
			    /* 当已经登录了一个不同的账号在本浏览器，那未退出前不允许再登陆别的账号 */
			    if(user !=null && !user.getLogName().equals(logName)) {
                    //WebUtils.redirectToSavedRequest(request, response, getSuccessUrl());
                    String LoginUrl = getLoginUrl() + (getLoginUrl().contains("?") ? "&" : "?") + "anotherUser=1&username="+user.getLogName();
                    WebUtils.issueRedirect(request, response, LoginUrl);
                    return true;
                }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

	/* 
	 *  @create time : 2016-10-11 上午11:00:00
	 *  @author : Alex Tan
	 *  @comments : 未登录用户的处理接口，只处理post请求，假如验证码不对，则再度返回login
	 *  			否则调用super接口，它会执行shiro login接口，调用Realm链
	 */
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response,
			Object mappedValue) throws Exception {
		
		int port = request.getServerPort();
		int local_port = request.getLocalPort();
		LogHelper.getLogger().debug("local "+local_port+" server "+port);
		/* 如果不是表单提交，则直接略过 */
		if(!"post".equalsIgnoreCase(WebUtils.toHttp(request).getMethod()))
			return true;
		
		String AuthCode = request.getParameter("authCode");
		LogHelper.getLogger().debug("AuthCode "+AuthCode);
		String AuthImg = (String)WebUtils.toHttp(request).getSession().getAttribute("securityCode");
		
		/* 假设验证码不对，则不再继续，直接重定向回登录界面 */
		if(AuthCode == null || !AuthCode.equalsIgnoreCase(AuthImg)) {
			String LoginUrl = getLoginUrl() + (getLoginUrl().contains("?")?"&":"?") + "AuthCodeFailed=1";
			WebUtils.issueRedirect(request, response, LoginUrl);
			return true;
		}
		return super.onAccessDenied(request, response, mappedValue);
	}

	/* 
	 *  @create time : 2016-10-11 上午11:01:51
	 *  @author : Alex Tan
	 *  @comments : shiro Realm验证通过后调用的接口，会直接跳转successUrl
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		
		TblUserDimBo user = IUserService.getUserByName(token.getPrincipal().toString());
		TblUserDimBo oldUser = IUserService.currentUser();
		if(oldUser!=null)
			LogHelper.getLogger().debug(oldUser.getLogName());
		WebUtils.toHttp(request).getSession().setAttribute(TblUserDimBo.USER_INFO_REFERENCE, user);
		user.setLastLogTime(DateUtil.getTimeNowFmtSec());
		IUserService.save(user);
		/* 移除掉登录前保存的url, 因为经常保存的iframe url */
		getSubject(request,response).getSession().removeAttribute(WebUtils.SAVED_REQUEST_KEY);
		return super.onLoginSuccess(token, subject, request, response);
	}

}
